﻿
@{
    ViewBag.Title = "聊天";
}

<style type="text/css">   
    .onLineUserPanel,.discussionPanel {
        border: solid 1px #7f8c8d;
        padding: 10px;
    }
        .onLineUserPanel .onLineUserDiv {
            margin-right: 0px;
            margin-left: 0px;
        }
        .onLineUserPanel .onLineUserDiv div:nth-child(2n+1) {
            background: #bdc3c7
        }
        .onLineUserPanel .onLineUserDiv div:nth-child(2n+2) {
            background: #95a5a6
        }
    #discussion li {
        background-color: #ecf0f1;
    }

    #discussion .me {
        background-color: #bdc3c7;
    }

    .discussionPanel{
        margin-top:20px;
    }
</style>

<h2>Chat</h2>

<div>
    <div class="container">
        <div class="onLineUserPanel">
            <h4>在线用户</h4>
            <hr />
            <div class="onLineUserDiv row">
            </div>
        </div>
        <div class=" row">
            <div class="col-lg-12">
                <strong>用户名称：</strong>
                <label id="displayname" />
            </div>
            <div class="col-lg-12">
                <input type="text" id="Message" />
                <button id="Send">发送</button>
            </div>
        </div>
        <div class="discussionPanel">
            <h4>讨论记录</h4>
            <hr />
            <ul id="discussion"></ul>
        </div>
    </div>
</div>
@section  scripts{
    <!--Script references. -->
    <!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
    <!--Reference the SignalR library. -->
    <script src="~/Scripts/jquery-3.3.1.min.js"></script>
    <script src="~/Scripts/jquery.signalR-2.4.1.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/signalr/hubs"></script>
    <!--SignalR script to update the chat page and send messages.-->
    <script type="text/javascript">
        window.onclose = function () {
            debugger;
            if (confirm("确认关闭吗？")) {
                return true;
            } else {
                return false;
            }
        }
        $(function () {
            // 启用日志
            $.connection.hub.logging = true;
            $('#displayname').text(prompt('输入用户名', ''));
            // Set initial focus to message input box.
            $('#Message').focus();
            var chat = $.connection.chatHub;
            chat.client.addNewMessageToPage = function (name, message) {
                $("#discussion").append('<li><strong>' + htmlEncode(name) + '：</strong>' + htmlEncode(message) + '</li>');
            }

            chat.client.onLineUsersChange = refreshOnLineUsers;
            
            $.connection.hub.qs = { userName: $('#displayname').text() };

            $.connection.hub.starting(function () {
                console.log("开始建立连接");
            });
            $.connection.hub.received(function (data) {
                console.log("接受到数据：");
                console.log(data);
            });
            $.connection.hub.connectionSlow(function () {
                console.log("连接不稳定");
            });
            $.connection.hub.reconnecting(function () {
                console.log("开始重新建立连接");
            });
            $.connection.hub.reconnected(function () {
                console.log("重新建立连接完成");
            });
            $.connection.hub.stateChanged(function (state) {
                console.log("连接状态改变：");
                console.log(state);
            });
            $.connection.hub.disconnected(function () {
                console.log("连接状断开：");
            });

            /**
             * 开启连接
             * connection.start({ transport: ['webSockets','longPolling'] });
             * 尝试 WebSocket，如果失败，直接访问长轮询
             * 可设定值：
             * webSockets
             * foreverFrame
             * serverSentEvents
             * longPolling
              */
            $.connection.hub.start({ transport: ['webSockets', 'longPolling'] }).done(function () {

                //chat.server.getAllOnLineUser().done(refreshOnLineUsers);

                $("#Send").on("click", function () {
                    var name = $("#displayname").text();
                    var message = $("#Message").val();
                    var users = [];
                    chat.server.send({ ReceiveUser: getSelectedUser(), Msg: message, SendBy: name })
                        .done(function (data) {
                            $("#discussion").append('<li class="me"><strong>我：</strong>' + htmlEncode(message) + '</li>');
                            console.log("send done:");
                            console.log(data);
                        });
                    $('#Message').val('').focus();
                });
            });

            function refreshOnLineUsers(data) {
                console.log(data);
                var selectedUser = getSelectedUser();
                $(".onLineUserDiv").children().remove();
                $.each(data, function () {
                    var me = this;
                    if (!me || me.toString() === $("#displayname").text()) return;
                    var row = $("<div class='col-lg-12'>").appendTo($(".onLineUserDiv"));
                    var chickebox = $("<input type='checkbox' id='" + me + "'>").appendTo(row);
                    $("<label for='" + me + "'>").text(me).appendTo(row);
                    $.each(selectedUser, function () {
                        if (this.toString() === me.toString())
                            chickebox.attr('checked', true);
                    });
                });
            }

            function htmlEncode(value) {
                var encodedValue = $('<div />').text(value).html();
                return encodedValue;
            }

            function getSelectedUser() {
                var users = [];
                $.each($(".onLineUserDiv input[type='checkbox']:checked"), function () { users.push(this.id) });
                return users;
            }

        });
    </script>
}
